package com.feonix.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.reflect.FieldUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

public class ReflectionUtils {
	private static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);

	static {
		DateConverter dateConverter = new DateConverter();
		dateConverter.setUseLocaleFormat(true);
		dateConverter.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" });
		ConvertUtils.register(dateConverter, Date.class);
	}

	/**
	 * 调用Getter方法.
	 * 
	 * @param obj
	 * @param propertyName
	 * @return
	 */
	public static Object invokeGetterMethod(Object obj, String propertyName) {
		String str = "get" + StringUtils.capitalize(propertyName);
		return invokeMethod(obj, str, new Class[0], new Object[0]);
	}

	/**
	 * 调用Setter方法.使用value的Class来查找Setter方法.
	 * 
	 * @param obj
	 * @param propertyName
	 * @param value
	 */
	public static void invokeSetterMethod(Object obj, String propertyName, Object value) {
		invokeSetterMethod(obj, propertyName, value, null);
	}

	/**
	 * 调用Setter方法.
	 * 
	 * @param obj
	 * @param propertyName
	 * @param value
	 * @param propertyType
	 *            用于查找Setter方法,为空时使用value的Class替代.
	 */
	public static void invokeSetterMethod(Object obj, String propertyName, Object value, Class<?> propertyType) {
		Class<?> clazz = (propertyType != null) ? propertyType : value.getClass();
		String str = "set" + StringUtils.capitalize(propertyName);
		invokeMethod(obj, str, new Class[] { clazz }, new Object[] { value });
	}

	/**
	 * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
	 * 
	 * @param obj
	 * @param fieldName
	 * @return
	 */
	public static Object getFieldValue(Object obj, String fieldName) {
		Field field = getAccessibleField(obj, fieldName);

		if (field == null) {
			throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
		}

		Object object = null;
		try {
			object = field.get(obj);
		} catch (IllegalAccessException illegalAccessException) {
			logger.error("不可能抛出的异常{}", illegalAccessException.getMessage());
		}
		return object;
	}

	/**
	 * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
	 * 
	 * @param obj
	 * @param fieldName
	 * @param value
	 */
	public static void setFieldValue(Object obj, String fieldName, Object value) {
		Field field = getAccessibleField(obj, fieldName);

		if (field == null) {
			throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
		}
		try {
			field.set(obj, value);
		} catch (IllegalAccessException illegalAccessException) {
			logger.error("不可能抛出的异常:{}", illegalAccessException.getMessage());
		}
	}

	/**
	 * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null.
	 * 
	 * @param obj
	 * @param fieldName
	 * @return
	 */
	public static Field getAccessibleField(Object obj, String fieldName) {
		Assert.notNull(obj, "object不能为空");
		Assert.hasText(fieldName, "fieldName");
		for (Class<? extends Object> clazz = obj.getClass(); clazz != Object.class; clazz = clazz.getSuperclass())
			try {
				Field field = clazz.getDeclaredField(fieldName);
				field.setAccessible(true);
				return field;
			} catch (NoSuchFieldException noSuchFieldException) {
			}
		return null;
	}

	/**
	 * 直接调用对象方法, 无视private/protected修饰符. 用于一次性调用的情况.
	 * 
	 * @param obj
	 * @param methodName
	 * @param parameterTypes
	 * @param args
	 * @return
	 */
	public static Object invokeMethod(Object obj, String methodName, Class<?>[] parameterTypes, Object[] args) {
		Method method = getAccessibleMethod(obj, methodName, parameterTypes);
		if (method == null) {
			throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
		}
		try {
			return method.invoke(obj, args);
		} catch (Exception exception) {
			throw convertReflectionExceptionToUnchecked(exception);
		}
	}

	/**
	 * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null.
	 * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object...
	 * args)
	 * 
	 * @param obj
	 * @param methodName
	 * @param parameterTypes
	 * @return
	 */
	public static Method getAccessibleMethod(Object obj, String methodName, Class<?>[] parameterTypes) {
		Assert.notNull(obj, "object不能为空");

		for (Class<? extends Object> clazz = obj.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
			try {
				Method method = clazz.getDeclaredMethod(methodName, parameterTypes);

				method.setAccessible(true);

				return method;
			} catch (NoSuchMethodException noSuchMethodException) {
			}
		}
		return null;
	}

	/**
	 * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. eg. public UserDao
	 * extends HibernateDao
	 * 
	 * @param clazz
	 * @return
	 */
	public static Class<?> getSuperClassGenricType(Class<?> clazz) {
		return getSuperClassGenricType(clazz, 0);
	}

	/**
	 * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. 如public UserDao
	 * extends HibernateDa
	 * 
	 * @param clazz
	 * @param index
	 * @return
	 */
	public static Class<?> getSuperClassGenricType(Class<?> clazz, int index) {
		Type type = clazz.getGenericSuperclass();

		if (!(type instanceof ParameterizedType)) {
			logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
			return Object.class;
		}

		Type[] arrayOfType = ((ParameterizedType) type).getActualTypeArguments();

		if ((index >= arrayOfType.length) || (index < 0)) {
			logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
					+ arrayOfType.length);
			return Object.class;
		}
		if (!(arrayOfType[index] instanceof Class)) {
			logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
			return Object.class;
		}

		return (Class<?>) arrayOfType[index];
	}

	/**
	 * 提取集合中的对象的属性(通过getter函数), 组合成List.
	 * 
	 * @param collection
	 * @param propertyName
	 * @return
	 */
	public static List<Object> convertElementPropertyToList(Collection<?> collection, String propertyName) {
		ArrayList<Object> list = new ArrayList<Object>();
		try {
			for (Iterator<?> iterator = collection.iterator(); iterator.hasNext();) {
				Object obj = iterator.next();
				list.add(PropertyUtils.getProperty(obj, propertyName));
			}
		} catch (Exception exception) {
			throw convertReflectionExceptionToUnchecked(exception);
		}

		return list;
	}

	/**
	 * 提取集合中的对象的属性(通过getter函数), 组合成由分割符分隔的字符串.
	 * 
	 * @param collection
	 * @param propertyName
	 * @param separator
	 * @return
	 */
	public static String convertElementPropertyToString(Collection<?> collection, String propertyName,
			String separator) {
		List<Object> list = convertElementPropertyToList(collection, propertyName);
		return StringUtils.join(list, separator);
	}

	/**
	 * 转换字符串到相应类型.
	 * 
	 * @param value
	 *            待转换的字符串
	 * @param toType
	 *            转换目标类型
	 * @return
	 */
	public static Object convertStringToObject(String value, Class<?> toType) {
		try {
			return ConvertUtils.convert(value, toType);
		} catch (Exception exception) {
			throw convertReflectionExceptionToUnchecked(exception);
		}
	}

	/**
	 * 将反射时的checked exception转换为unchecked exception.
	 * 
	 * @param e
	 * @return
	 */
	public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
		if ((e instanceof IllegalAccessException) || (e instanceof IllegalArgumentException)
				|| (e instanceof NoSuchMethodException))
			return new IllegalArgumentException("Reflection Exception.", e);
		if (e instanceof InvocationTargetException)
			return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException());
		if (e instanceof RuntimeException) {
			return ((RuntimeException) e);
		}
		return new RuntimeException("Unexpected Checked Exception.", e);
	}

	/**
	 * 得到新的对象
	 * 
	 * @param cls
	 * @return
	 */
	public static final <T> T getNewInstance(Class<T> cls) {
		try {
			return cls.newInstance();
		} catch (InstantiationException instantiationException) {
			instantiationException.printStackTrace();
		} catch (IllegalAccessException instantiationException) {
			instantiationException.printStackTrace();
		}
		return null;
	}

	/**
	 * 最稳妥的反射修改静态变量
	 * 
	 * @param clazz
	 * @param fieldName
	 * @param value
	 * @param forceAccess
	 */
	public static void writeStaticField(Class<?> clazz, String fieldName, Object value, boolean forceAccess) {
		try {
			FieldUtils.writeDeclaredStaticField(clazz, fieldName, value, forceAccess);
		} catch (IllegalAccessException illegalAccessException) {
			illegalAccessException.printStackTrace();
		}
	}
}
